package top.wbhzx.controller;

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import top.wbhzx.mapper.DirMapper;
import top.wbhzx.mapper.FileMapper;
import top.wbhzx.pojo.Dir;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value="/file")
public class FileController {

	@Autowired
	private DirMapper dirMapper;
	@Autowired
	private FileMapper fileMapper;
	
	@RequestMapping(value="/uploadFile.json" ,produces="application/json;charset=UTF-8" )  
    public @ResponseBody Object importPicFile1(@RequestParam MultipartFile file,@RequestParam Integer id){
        
		Dir dir = dirMapper.selectByPrimaryKey(id);
		
		Map<String,Object> map= new HashMap<String,Object>();  
        if(file.isEmpty()){  
             map.put( "result", "error");  
             map.put( "msg", "上传文件不能为空" );
             return JSON.toJSONString(map);
       } else{
    	   	//有后缀
             String originalFilename=file.getOriginalFilename();  
             //不包括后缀
             String fileBaseName=FilenameUtils.getBaseName(originalFilename);   
              try{   
                    //创建要上传的路径
                  File fdir = new File("D:/wangpanfile"+dir.getDirPath());
                  if (!fdir.exists()) { 
                      fdir.mkdirs(); 
                      }
                  //文件上传到路径下
                   FileUtils. copyInputStreamToFile(file.getInputStream(), new File(fdir,originalFilename)); 
                   
                   //添加数据
                   top.wbhzx.pojo.File myFile = new top.wbhzx.pojo.File();
                   myFile.setDirId(dir.getId());
                   myFile.setFileName(originalFilename);
                   myFile.setFileSize(file.getSize());
                   myFile.setFileStatus(1);
                   myFile.setFileType("暂无");
                   myFile.setFileUploadTime(System.currentTimeMillis());
                   if(fileMapper.insertSelective(myFile) < 1) {
                	   map.put( "msg", "载入数据库失败" );
                	   return JSON.toJSONString(map);
                   }
                   
                    //coding  
                   map.put( "result", "success");
                   map.put( "msg", "上传文件成功" );
                   return JSON.toJSONString(map);
             } catch (Exception e) {  
                   map.put( "result", "error");  
                   map.put( "msg",e.getMessage());
                   return JSON.toJSONString(map);
                     
             }  
       }
	}
	
	
	/**
     * 文件下载
     * @throws IOException 
     */
    @RequestMapping(value="/download",method=RequestMethod.GET)
    public void download(@RequestParam(value="path")String filename,
            HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        //模拟文件，myfile.txt为需要下载的文件  
        String path = "D:/wangpanfile"+filename;
        //获取输入流  
        InputStream bis = new BufferedInputStream(new FileInputStream(new File(path)));
        //转码，免得文件名中文乱码  
        filename = URLEncoder.encode(filename,"UTF-8");  
        //设置文件下载头  
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);    
        //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型    
        response.setContentType("multipart/form-data");   
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());  
        int len = 0;  
        while((len = bis.read()) != -1){  
            out.write(len);  
            out.flush();  
        }  
        out.close();  
    }
	
	
}
